import BorderlessButton from "@/src/components/borderless-button"
import { TempState } from "@/src/dva/models/temp"
import { State } from "@/src/dva/state"
import Global from "@/src/lib/global"
import GoodsCartModel from "@/src/lib/models/goods_cart_model"
import { View, Image, Text, ITouchEvent } from "@tarojs/components"
import React, { Fragment } from "react"
import { connect } from "react-redux"
import Taro from '@tarojs/taro';
import FreeTitle from "@/src/components/free"

import "./item.scss"
import { EventKey } from "@/src/consts"

interface ItemProps {
    model: GoodsCartModel
    dispatch?: any
    temp: TempState
}


class Item extends React.Component<ItemProps> {

    isMoving = false
    isOpenMenu = false
    beginTouchPoint?: { x: number, y: number }
    currentTouchPoint?: { x: number, y: number }

    componentDidMount() {
        Taro.eventCenter.on(EventKey.ShopcartItemMenuTrialOpen, this.onShopcartItemMenuTrialOpen)
    }

    componentWillUnmount() {
        Taro.eventCenter.off(EventKey.ShopcartItemMenuTrialOpen, this.onShopcartItemMenuTrialOpen)
    }

    onShopcartItemMenuTrialOpen = (item: Item) => {
        if (item != this && this.isOpenMenu) {
            this.isOpenMenu = false
            this.setState({})
        }
    }

    onSelectBtnClick = () => {
        const { model, dispatch, temp } = this.props
        const { selectedGoodsIds } = temp.shopcart

        if (model.loc_isSelling) {
            if (selectedGoodsIds.has(model.goodsid)) {
                dispatch({
                    type: "temp/shopcartRemoveSelectedGoodsId",
                    payload: model.goodsid
                })

            } else {
                dispatch({
                    type: "temp/shopcartInsertSelectedGoodsId",
                    payload: model.goodsid
                })
            }
        }
    }

    onAdjustAddBtnClick = (e: ITouchEvent<any>) => {

        const { model, dispatch } = this.props
        // console.log('model',model)
        e.stopPropagation()
        e.preventDefault()
        // console.log('e',e);
        let goodsprice: string = '0';
        // 判断是否有活动价格
        if (Number.parseFloat(model.activityprice) > 0) {
            goodsprice = model.activityprice
        } else {
            goodsprice = model.realprice
        }
        // return
        dispatch({
            type: "cart/adjustNum",
            payload: {
                goodsid: model.goodsid,
                addnum: "1",
                goodsprice
            }
        })
    }

    onAdjustMinusBtnClick = (e: ITouchEvent<any>) => {
        const { model, dispatch } = this.props

        e.stopPropagation()
        e.preventDefault()
        let goodsprice: string = '0';
        // 判断是否有活动价格
        if (Number.parseFloat(model.activityprice) > 0) {
            goodsprice = model.activityprice
        } else {
            goodsprice = model.realprice
        }
        dispatch({
            type: "cart/adjustNum",
            payload: {
                goodsid: model.goodsid,
                addnum: "-1",
                goodsprice
            }
        })
    }

    onGoodsItemClick = (e: ITouchEvent<any>) => {
        const { model } = this.props

        e.stopPropagation()
        e.preventDefault()

        Global.navigateTo("pages/goodsdetail/index", {
            params: { id: model.goodsid }
        })
    }

    onTouchStart = (e: ITouchEvent<any>) => {

        if (this.isOpenMenu) {
            e.stopPropagation()
            e.preventDefault();
            // this.isMoving = false
            // this.isOpenMenu = false
            // this.setState({})
            return
        }

        Taro.eventCenter.trigger(EventKey.ShopcartItemMenuTrialOpen, this)

        let point = e.touches[0]
        // console.log('滑动',point)
        if (point) {
            this.beginTouchPoint = {
                x: point.clientX,
                y: point.clientY
            }
        }
    }

    onTouchMove = (e: ITouchEvent<any>) => {
        // console.log('e',e)
        if (!this.beginTouchPoint) {
            this.isMoving = false
            this.isOpenMenu = false
            this.setState({})
            return
        }

        let point = e.touches[0]
        if (point) {
            this.currentTouchPoint = {
                x: point.clientX,
                y: point.clientY
            }

            if (this.isMoving) {
                e.stopPropagation()
                e.preventDefault()
                // console.log('ssss')
                this.setState({})
            } else {

                if (this.currentTouchPoint.y > this.beginTouchPoint.y + 10 ||
                    this.currentTouchPoint.y < this.beginTouchPoint.y - 10) {
                    // console.log('aaaasas')
                    this.currentTouchPoint = undefined
                    this.isMoving = false

                } else if (this.currentTouchPoint.x < this.beginTouchPoint.x - 10) {
                    this.isMoving = true
                    // console.log('bbbbb')
                }
            }
        } else {
            this.isMoving = false
            this.isOpenMenu = false
        }
    }

    onTouchEnd = (e: ITouchEvent<any>) => {
        if (this.isMoving) {
            e.stopPropagation()
            e.preventDefault()

            if (this.currentTouchPoint!.x - this.beginTouchPoint!.x <= -100) {
                this.isOpenMenu = true
                // console.log('ssssssbbbbbbb')
            } else {
                this.isOpenMenu = false
                // console.log('cccccc')
            }

            this.beginTouchPoint = undefined
            this.currentTouchPoint = undefined
            this.isMoving = false
            this.setState({})
        }
    }

    onCloseMenu = (e: ITouchEvent<any>) => {
        e.stopPropagation()
        e.preventDefault()

        this.isOpenMenu = false
        this.setState({})
    }


    onMenuDeleteItemClick = (e: ITouchEvent<any>) => {

        const { dispatch, model } = this.props

        dispatch({
            type: "cart/removeGoods",
            payload: [model.goodsid]
        })
        this.onCloseMenu(e)
    }

    render() {
        const { model, temp } = this.props
        const { selectedGoodsIds } = temp.shopcart;
        // const { freetitle } = model;
        console.log('model购物', model)
        let isSelected = selectedGoodsIds.has(model.goodsid)

        let moveDistance = 0
        if (this.isMoving && this.currentTouchPoint && this.beginTouchPoint) {
            moveDistance = Math.min(0, Math.max(-150, this.currentTouchPoint.x - this.beginTouchPoint.x))
        } else if (this.isOpenMenu) {
            moveDistance = -150
        }

        return (
            <Fragment>


                <View className="item">

                    <View className="back-menu">
                        <View className="back-menu-item" onClick={this.onMenuDeleteItemClick}>
                            <View className="back-menu-item-delete">删除</View>
                        </View>
                    </View>

                    <View
                        className="item-content"
                        style={{ left: `${moveDistance}rpx` }}
                        onTouchStart={this.onTouchStart}
                        onTouchMove={this.onTouchMove}
                        onTouchEnd={this.onTouchEnd}>

                        <BorderlessButton className="item-select-btn" backgroundImage={isSelected ? "icon_selected@3x.png" : "icon_unselect@3x.png"} onClick={this.onSelectBtnClick} />

                        <View className="goods-item" onClick={this.onGoodsItemClick}>

                            <Image className="goods-item-img" src={model.pic} mode="aspectFill" />

                            <View className="goods-item-profile">
                                <View>
                                    <View className="goods-item-title">{`${model.title} ${model.tip}`}</View>
                                    <View className="goods-item-subtitle">{model.kouwei} {model.hanliang}</View>
                                </View>

                                <View>
                                    <View>
                                        {/* <Text className="goods-item-price">￥{model.num>'2'? model.realprice : model.activityprice }</Text> */}
                                        <Text className="goods-item-price">￥{model.goodsprice ? model.goodsprice : model.activityprice > 0 ? model.activityprice : model.realprice}</Text>
                                        <Text className="goods-item-price-origin">￥{model.showprice}</Text>
                                    </View>

                                    <View className="goods-num-adjuest">
                                        <BorderlessButton backgroundImage="icon_minus@3x.png" className="goods-num-adjuest-btn" onClick={this.onAdjustMinusBtnClick} />
                                        <Text>{(model as GoodsCartModel).num}</Text>
                                        <BorderlessButton backgroundImage="add@3x.png" className="goods-num-adjuest-btn" onClick={this.onAdjustAddBtnClick} />
                                    </View>
                                </View>
                            </View>
                        </View>

                        <View style={{ width: "100%", height: "100%", position: "absolute", left: "0", top: "0", display: this.isOpenMenu ? "block" : "none" }}
                            onClick={this.onCloseMenu}
                        />

                    </View>

                </View>
                {/* 新增 <View className="item_xin">
                        <View className="buttns">赠品</View>
                        <View className="texts">{model.freetitle}</View>
                    </View> */}
                {
                    isSelected && model.freetitle?<FreeTitle freetitle={model.freetitle}></FreeTitle> :null
                }
               
            </Fragment>
        )
    }
}


export default connect((state: State) => ({ temp: state.temp }), (dispatch) => ({ dispatch }))(Item)